package com.woniu.listener;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.woniu.intlet.vo.WorkerVo;
import com.woniu.outlet.dao.ReliablePoMapper;
import com.woniu.outlet.po.ProSchedulingPo;
import com.woniu.outlet.po.ReliablePo;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 生产排程消息监听
 */
@Component
public class ProScheduingMessageListener {

    @Autowired
    private ReliablePoMapper reliablePoMapper;
    @Autowired
    private JavaMailSenderImpl javaMailSender;
    @Value("${spring.mail.username}")
    private String sendPreson;

    @RabbitListener(queues = "pro_queue")
    public void getMessage(Message message, Channel channel){
        //消息去重
        String messageId = message.getMessageProperties().getClusterId();
        ReliablePo reliablePo = new ReliablePo();
        reliablePo.setMessageid(Integer.parseInt(messageId));
        try {
            reliablePoMapper.insert(reliablePo);
        } catch (Exception e) {
            e.printStackTrace();
            //拒绝应答
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
        //发送消息至审核人员
        String[] split = new String(message.getBody()).split("-");
        ProSchedulingPo proSchedulingPo = JSON.parseObject(split[0], ProSchedulingPo.class);
        WorkerVo workerVo = JSON.parseObject(split[1], WorkerVo.class);
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        if (proSchedulingPo.getSpare1().equals("1")){
            mailMessage.setSubject("紧急的生产排程单");
            mailMessage.setText("你有一条最新的生产排程单信息,该生产排程优先级为1,请尽快安排生产人员进行生产; 生产排产id:"+proSchedulingPo.getId());
        }else {
            mailMessage.setSubject("普通的生产排程单");
            mailMessage.setText("你有一条最新的生产排程单信息,该生产排程优先级为"+proSchedulingPo.getSpare1()+",请尽快安排生产人员进行生产; 生产排产id:"+proSchedulingPo.getId());
        }
        mailMessage.setTo(workerVo.getEmail());    //收件人的邮箱
        mailMessage.setFrom(sendPreson);  //发件人的邮箱，和配置的username保持一致
        javaMailSender.send(mailMessage);
    }

}
